<template>
  <a-modal :title="title" :width="800" :maskClosable="false" :visible="visible" @cancel="visible = false">
    <a slot="footer">
      <a-button v-if="cancelText" @click="visible = false">{{ cancelText }}</a-button>
      <a-button v-if="okText == '确定'" type="primary" :loading="button_loading" @click="handleSubmit">{{ okText }}</a-button>
      <a-button v-if="okText == '关闭'" type="primary" @click="visible = false">{{ okText }}</a-button>
    </a>
    <a-row style="margin-bottom:10px">
      <a-button type="primary" @click="newRentLog" icon="plus">添加</a-button>
    </a-row>
    <a-spin :indicator="indicator" :spinning="spinning" :tip="tip">
      <div class="spin-content">
        <a-table size="small" bordered :rowKey="record => record.ID" :columns="columns" :dataSource="data" :rowClassName="setRowClassName">
          <template slot="answerName" slot-scope="text, record">
            <a-input v-if="record.editable" style="margin: -5px 0" :value="text" @change="e => handleInputChange(e, record.id, 'answerName')" />
            <template v-else>{{ text }}</template>
          </template>
          <template slot="score" slot-scope="text, record">
            <a-input-number v-if="record.editable" style="margin: -5px 0" :value="text" @change="e => handleNumChange(e, record.id, 'score')" />
            <template v-else>{{ text }}</template>
          </template>
          <span slot="action" slot-scope="text, record">
            <template v-if="record.editable">
              <span v-if="record.isNew">
                <a @click="saveRow(record, 'add')">保存</a>
                <a-divider type="vertical" />
                <a-popconfirm title="是否取消新增？" @confirm="cancel(record.ID, 'add')">
                  <a>取消</a>
                </a-popconfirm>
              </span>
              <span v-else>
                <a @click="saveRow(record, 'update')">保存</a>
                <a-divider type="vertical" />
                <a @click="cancel(record.ID, 'update')">取消</a>
              </span>
            </template>
            <span v-else>
              <a type="link" @click="toggle(record)">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm title="是否要删除此行？" @confirm="remove(record.id)">
                <a>删除</a>
              </a-popconfirm>
            </span>
          </span>
        </a-table>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { questionBankAnswerList, questionBankAnswerInfo, questionBankAnswerSave, questionBankAnswerDel } from '@/api/question'
import { deleteChildrenIfNull2 } from '@/utils/util'
import { questionCategoryList } from '@/api/question'
import { uploadImage, getImg, studentInfo } from '@/api/students'
import { mapActions, mapGetters } from 'vuex'
import { dropList } from '@/api/drop'
import dropValue from '@/views/dropValue'
import moment from 'moment'
export default {
  components: {},
  props: {
    display: {
      type: String,
      required: false
    }
  },
  data() {
    return {
      a: null,
      headers: {
        authorization: 'authorization-text'
      },
      currentId: null,
      required: false,
      indicator: <a-icon type="loading" style="font-size: 24px" spin />,
      form: this.$form.createForm(this),
      button_loading: false,
      spinning: false,
      tip: null,
      title: '添加题库信息',
      visible: false,
      uploadParams: {
        tablename: 'Budget',
        signname: null
      },
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        }
      },
      formItemLayout1: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      },
      okText: '确定',
      cancelText: '取消',
      ageGroup: [],
      ageGroupDrop: [],
      ageGroupValue: null,
      questionDict: [],
      columns: [
        {
          title: '选项名称',
          dataIndex: 'answerName',
          key: 'answerName',
          align: 'center',
          scopedSlots: { customRender: 'answerName' }
        },
        {
          title: '分数',
          dataIndex: 'score',
          key: 'score',
          align: 'center',
          scopedSlots: { customRender: 'score' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          width: 100,
          align: 'center'
        }
      ],
      data: [],
      queryParam: {
        questionBankID: null
      }
    }
  },
  watch: {},
  computed: { ...mapGetters(['token']) },
  methods: {
    moment,
    show(id) {
      this.data = []
      this.visible = true
      this.queryParam.questionBankID = id
      this.initData(this.queryParam)
    },
    initData(data) {
      this.spinning = true
      questionBankAnswerList(data)
        .then(res => {
          this.data = res.data
          this.data.map((a, index) => {
            // a.payTime = tranDate(a.payTime)
            // // a.Time = `${a.Year}-${a.Month}`
            a.editable = false
            a.ID = index
          })
          // this.pagination.total = res.page.RecordCount
        })
        .finally(() => {
          this.spinning = false
        })
    },
    handleDateChange(date, dateString, id, column) {
      const newData = [...this.data]
      const target = newData.find(item => id === item.id)
      if (target) {
        target[column] = dateString
        this.data = newData
      }
    },
    handleNumChange(value, id, column) {
      const newData = [...this.data]
      const target = newData.find(item => id === item.id)
      if (target) {
        target[column] = value
        this.data = newData
      }
    },
    handleInputChange(value, id, column) {
      const newData = [...this.data]
      const target = newData.find(item => id === item.id)
      if (target) {
        target[column] = value.target.value
        this.data = newData
      }
    },
    newRentLog() {
      const length = this.data.length
      this.data.push({
        ID: length === 0 ? 1 : parseInt(this.data[length - 1].ID + 1),
        answerName: null,
        score: 0,
        editable: true,
        isNew: true
      })
    },
    toggle(data) {
      const target = this.data.find(item => item.id === data.id)
      target._originalData = { ...target }
      target.editable = !target.editable
      this.$forceUpdate()
    },
    cancel(key, action) {
      if (action == 'update') {
        const target = this.data.find(item => item.ID === key)
        Object.keys(target).forEach(key => {
          target[key] = target._originalData[key]
        })
        target._originalData = undefined
        this.$forceUpdate()
      } else {
        this.data = this.data.filter(a => a.ID != key)
      }
    },
    remove(key) {
      let _arr = []
      _arr.push(key)
      questionBankAnswerDel(_arr).then(res => {
        this.initData(this.queryParam)
      })
    },
    saveRow(record, action) {
      const { id, answerName, score } = record
      if (!answerName || score == null) {
        this.spinning = false
        this.$message.error('请填写完整信息。')
        return
      }
      if (action == 'add') {
        questionBankAnswerSave({
          id: id,
          questionBankID: this.queryParam.questionBankID,
          answerName: answerName,
          score: score,
          AddUserID: id != null ? null : this.token.id,
          UpdateUserID: id == null ? null : this.token.id
        }).then(() => {
          this.initData(this.queryParam)
          // const target = this.data.find(item => item.id === ID)
          // target.editable = false
          // target.isNew = false
        })
      } else {
        questionBankAnswerSave({
          id: id,
          questionBankID: this.queryParam.questionBankID,
          answerName: answerName,
          score: score,
          AddUserID: id != null ? null : this.token.id,
          UpdateUserID: id == null ? null : this.token.id
        }).then(() => {
          this.initData(this.queryParam)
          // const target = this.data.find(item => item.id === ID)
          // target.editable = false
          // target.isNew = false
        })
      }
    },
    handleSubmit() {
      this.visible = false
    },
    setRowClassName(record, idx) {
      return idx % 2 == 1 ? 'bg-zebra-pattern' : ''
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    pageOnChange(index, pageSize) {
      this.spinning = true
      Object.assign(this.pagination, {
        current: index,
        pageSize,
        index
      })
      Object.assign(this.queryParam, {
        pageSize,
        index
      })
      this.initData(this.queryParam)
    }
  },
  created() {
    // dropList({ categoryId: dropValue.ageGroupDict }).then(res => {
    //   this.ageGroup = res
    //   this.ageGroupDrop = res
    //   this.removeChildrenIfNUll(this.ageGroupDrop)
    // })
    dropList({ categoryId: dropValue.questionDict }).then(res => {
      this.questionDict = res
    })
  },
  mounted() {}
}
</script>
<style lang="less" scoped>
/deep/.ant-card-head {
  color: #ffffff;
  background-color: @primary-color;
}
/deep/.ant-popover-inner-content {
  padding: 0;
}
.ant-form-item {
  margin-bottom: 4px;
}
.avatar-uploader > .ant-upload {
  width: 104px;
  height: 104px;
}
.ant-upload-list-picture-card-container {
  width: 104px;
  height: 104px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.notclickn {
  pointer-events: none;
}

.viewless {
  /deep/.ant-input-number {
    border: none;
    background: transparent;
  }

  /deep/.ant-input {
    border: none;
    background: transparent;
  }

  .ellipsis {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  /deep/.ant-input-disabled {
    color: rgba(0, 0, 0, 0.65);
    cursor: default;
  }

  /deep/.ant-select-disabled {
    color: rgba(0, 0, 0, 0.65);
  }

  // /deep/.ant-modal-content {
  //   pointer-events: unset;
  // }
  /deep/.ant-select-selection--single {
    border: none;
    background: transparent;
  }

  /deep/.ant-select-arrow .ant-select-arrow-icon {
    display: none;
  }

  /deep/.anticon {
    display: none;
  }
  /deep/.anticon-star {
    display: unset;
  }

  /deep/.vue-treeselect div,
  .vue-treeselect span {
    border: none;
  }

  /deep/.vue-treeselect__x-container {
    display: none;
  }

  /deep/.vue-treeselect__control-arrow-container {
    display: none;
  }
}
</style>
